#include "udp_echo_client.h"
#include "sys_plat.h"
#include <stdio.h>

int udp_echo_client_start(const char *ip, int port)
{
    // todo 先直接调用系统的socket相关接口
    // WSADATA wsdata;
    // WSAStartup(MAKEWORD(2, 2), &wsdata);

    int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    // struct timeval time;
    // time.tv_sec = 3;
    // time.tv_usec = 0;
    // setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&time, sizeof(time));
    if (s < 0)
    {
        printf("open socket faield!\n");
        return -1;
    }

    struct sockaddr_in addr;
    plat_memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(port);

    connect(s, (const struct sockaddr *)&addr, sizeof(addr));

    char buf[BUF_SIZE];
    while(fgets(buf, BUF_SIZE, stdin) != NULL){
        buf[BUF_SIZE - 1] = '\0';
        char *find = strchr(buf, '\n');
        *find = '\0';
        if(strcmp(buf, "quit") == 0 || strcmp(buf, "QUIT") == 0)
        {
            break;
        }

        // ssize_t size = sendto(s, buf, (int)strlen(buf), 0, (struct sockaddr *)&addr, sizeof(addr));
        ssize_t size = send(s, buf, (int)strlen(buf), 0);
        if(size < 0)
        {
            printf("send message failed!\n");
            break;
        }

        struct sockaddr_in from_addr;
        plat_memset(&from_addr, 0, sizeof(from_addr));
        int from_len = sizeof(from_addr);
        plat_memset(buf, 0, BUF_SIZE);
        size = recvfrom(s, buf, BUF_SIZE, 0, (struct sockaddr *)&from_addr, &from_len);
        // size = recv(s, buf, BUF_SIZE, 0);
        if(size < 0){
            printf("recv message failed!\n");
            break;
        }
        printf("recv message:%s\n", buf);
    }
    close(s);
    return 0;
}